package jinyilw.swing.visuals;

import jinyilw.swing.ColorTools;
import jinyilw.swing.ResourceManager;

import javax.swing.JDialog;
import javax.swing.JFrame;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Window;
import java.util.concurrent.Executors;

public class LaunchWindow extends Window// 启动窗
{
	private static final long serialVersionUID = -1620527224948235771L;
	Image image;
	public LaunchWindow() throws HeadlessException
	{
		super(null);
		setBackground(ColorTools.transparentColor);
	}

	public LaunchWindow(String str) throws HeadlessException
	{
		this();
		setLaunchImage(str);
	}

	public void setLaunchImage(String str)
	{
		image = ResourceManager.getBufferedImage(LaunchWindow.class, str);
		if (image != null)
		{
			setSize(image.getWidth(null), image.getHeight(null));
		}
	}

	public void customLaunch()
	{
		setLocationRelativeTo(null);
		setVisible(true);
	}

	public void launch()
	{
		if (image == null)
			return;
		setLocationRelativeTo(null);
		setVisible(true);
		Executors.newSingleThreadExecutor().execute(() -> {
			try
			{
				Thread.sleep(500);
				while (LaunchWindow.this.isVisible())
				{
					EventQueue.invokeLater(() -> {
						try
						{
							for (Window window : (Window[]) Window.class
									.getMethod("getWindows")
									.invoke(null))
								if ((window instanceof JFrame
										|| window instanceof JDialog)
										&& window.isShowing())
								{
									LaunchWindow.this.dispose();
									break;
								}
						} catch (Exception ex)
						{
							for (Frame frame : Frame.getFrames())
								if (frame.isShowing())
								{
									LaunchWindow.this.dispose();
									break;
								}
						}
					});
					Thread.sleep(200);
				}
			} catch (InterruptedException ex)
			{
				EventQueue.invokeLater(LaunchWindow.this::dispose);
			}
		});
	}

	@Override
	public void paint(Graphics g)
	{
		if (image != null)
			g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
	}
}
